package database;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import model.Endereco;
import model.Entidade;

public class EnderecoDAO extends DAOClass {
	
	private int lastPK = 0;
	
	@Override
	public <T> boolean inserir(T t) {
		Endereco end;
		if(t instanceof Endereco)
			end = (Endereco) t;
		else
			return false;
		
		PreparedStatement pstm;
		Connection conn = Conexao.getConexao();
		
		try {
			pstm = conn.prepareStatement("insert into endereco(logradouro, numero, complemento, bairro, cep, cidade, uf) values (?,?,?,?,?,?,?)", PreparedStatement.RETURN_GENERATED_KEYS);
			pstm.setString(1, end.getLogradouro());
			pstm.setString(2, end.getNumero());
			pstm.setString(3, end.getComplemento());
			pstm.setString(4, end.getBairro());
			pstm.setString(5, end.getCep());
			pstm.setString(6, end.getCidade());
			pstm.setString(7, end.getUf());
			
			pstm.execute();
			
			ResultSet generatedKeys = pstm.getGeneratedKeys();
			if(generatedKeys.next()){
				lastPK = generatedKeys.getInt(1);
			}
			
			pstm.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
		
		return true;
	}
	
	public int getLastPK(){
		return lastPK;
	}

	@Override
	public Entidade getById(int id) {
		Endereco end = null;
		
		try{
			Connection conn = Conexao.getConexao();
			PreparedStatement pstm = conn.prepareStatement("select * from endereco where id = ?");
			pstm.setInt(1, id);
			
			ResultSet rs = pstm.executeQuery();
			if(rs.next())
				end = preencheEndereco(rs);
			
			rs.close();
			pstm.close();
			conn.close();
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return end;
	}
	
	public Endereco preencheEndereco(ResultSet rs) throws SQLException{
		return new Endereco(rs.getString("logradouro"), rs.getString("numero"), rs.getString("complemento"),
				rs.getString("bairro"), rs.getString("cep"), rs.getString("cidade"), rs.getString("uf"));
	}
}
